package com.sec.etech.ism.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.ism.mapper.PreProjectFromCrmMapper;
import com.sec.etech.ism.model.IsmServiceDef;
import com.sec.etech.ism.model.PreProjectFromCrm;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmServiceDefService;
import com.sec.etech.ism.service.IsmTaskLogService;
import com.sec.etech.presale.model.OmsDto;
import com.sec.etech.presale.service.OmsService;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessException;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class IsmSwpServiceImpl implements IsmMethodService {

    @Resource
    OmsService omsService;
    @Resource
    IsmServiceDefService ismServiceDefService;
    @Resource
    IsmTaskLogService ismTaskLogService;
    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception {

        IsmServiceDef serviceDef = ismServiceDefService.getByCode(serviceCode);
        JSONObject params = businessParams.getJSONObject("input_params");
        String num = params.getString("num");
        String uniqueid = params.getString("uniqueid");
        if (StringUtil.isEmpty(num)){
            throw new BusinessException("缺少必要参数num,请填写SWP平台的业务编号!");
        }
        if (StringUtil.isEmpty(uniqueid)){
            throw new BusinessException("缺少必要参数uniqueid,请填写SWP平台的业务主键ID!");
        }

        OmsDto dto = new OmsDto();
        dto.setNum(num);
        dto.setUniqueid(uniqueid);
        dto.setData(params.getJSONObject("data"));

        JSONObject result = new JSONObject();

        boolean isOk = true;


        try{
            omsService.createByApi(dto);
            result.put("data", "调用成功");
            result.put("flag", "success");
        }catch (Throwable ex){
            ex.printStackTrace();
            result.put("data", ex.getMessage());
            result.put("flag", "fail");
            isOk = false;
        }

        JSONObject logObj = new JSONObject();
        logObj.put("service_code", serviceDef.getCode());
        logObj.put("service_name", serviceDef.getName());
        logObj.put("method_name", "ompProcess");
        logObj.put("input_json", businessParams);
        logObj.put("output_json", result);
        ismTaskLogService.saveLog(logObj);

        if (!isOk){
            throw new BusinessException(result.getString("data"));
        }

        return result;

    }




    @Override
    public String methodName() {
        return "swpCreate";
    }
}
